package com.docmgmt.mvp.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.docmgmt.mvp.entity.FolderEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * 文件夹数据访问层
 */
@Mapper
public interface FolderMapper extends BaseMapper<FolderEntity> {

    /**
     * 根据父文件夹ID查询子文件夹列表
     *
     * @param parentId  父文件夹ID（0表示根目录）
     * @param userId    用户ID（用于权限过滤）
     * @param sortBy    排序字段
     * @param sortOrder 排序方向
     * @return 子文件夹列表
     */
    @Select({
            "<script>",
            "SELECT id, name, parent_id, path, level, description, creator_id, owner_id,",
            "       sort_order, is_deleted, deleted_at, deleted_by, created_at, updated_at",
            "FROM doc_folder",
            "WHERE is_deleted = 0",
            "  AND parent_id = #{parentId}",
            "  AND (creator_id = #{userId} OR owner_id = #{userId})",
            "ORDER BY ${sortBy} ${sortOrder}",
            "</script>"
    })
    List<FolderEntity> listByParentId(
            @Param("parentId") Long parentId,
            @Param("userId") Long userId,
            @Param("sortBy") String sortBy,
            @Param("sortOrder") String sortOrder
    );

    /**
     * 查询用户有权访问的所有文件夹（用于构建树形结构）
     *
     * @param userId 用户ID
     * @return 文件夹列表
     */
    @Select({
            "SELECT id, name, parent_id, path, level, description, creator_id, owner_id,",
            "       sort_order, is_deleted, deleted_at, deleted_by, created_at, updated_at",
            "FROM doc_folder",
            "WHERE is_deleted = 0",
            "  AND (creator_id = #{userId} OR owner_id = #{userId})",
            "ORDER BY path ASC"
    })
    List<FolderEntity> listAccessibleFolders(@Param("userId") Long userId);

    /**
     * 根据路径查询文件夹
     *
     * @param path 文件夹路径
     * @return 文件夹实体
     */
    @Select({
            "SELECT id, name, parent_id, path, level, description, creator_id, owner_id,",
            "       sort_order, is_deleted, deleted_at, deleted_by, created_at, updated_at",
            "FROM doc_folder",
            "WHERE is_deleted = 0 AND path = #{path}",
            "LIMIT 1"
    })
    FolderEntity findByPath(@Param("path") String path);

    /**
     * 批量更新子文件夹的路径（用于文件夹重命名/移动时）
     *
     * @param oldPathPrefix 旧路径前缀
     * @param newPathPrefix 新路径前缀
     * @return 更新的记录数
     */
    @Update({
            "<script>",
            "UPDATE doc_folder",
            "SET path = CONCAT(#{newPathPrefix}, SUBSTRING(path, LENGTH(#{oldPathPrefix}) + 1)),",
            "    updated_at = NOW()",
            "WHERE is_deleted = 0",
            "  AND path LIKE CONCAT(#{oldPathPrefix}, '%')",
            "</script>"
    })
    int updateSubfolderPaths(
            @Param("oldPathPrefix") String oldPathPrefix,
            @Param("newPathPrefix") String newPathPrefix
    );

    /**
     * 统计文件夹下的子文件夹数量
     *
     * @param folderId 文件夹ID
     * @return 子文件夹数量
     */
    @Select("SELECT COUNT(*) FROM doc_folder WHERE is_deleted = 0 AND parent_id = #{folderId}")
    int countSubfolders(@Param("folderId") Long folderId);

    /**
     * 统计文件夹下的文件数量
     *
     * @param folderId 文件夹ID
     * @return 文件数量
     */
    @Select("SELECT COUNT(*) FROM doc_file WHERE is_deleted = 0 AND folder_id = #{folderId}")
    int countFiles(@Param("folderId") Long folderId);

    /**
     * 根据文件夹名称搜索文件夹（模糊匹配）
     *
     * @param keyword 搜索关键词
     * @return 匹配的文件夹列表
     */
    @Select("SELECT * FROM doc_folder WHERE name LIKE CONCAT('%', #{keyword}, '%') " +
            "AND is_deleted = 0 ORDER BY created_at DESC")
    List<FolderEntity> searchByName(@Param("keyword") String keyword);
}
